<template>
    <div class="login">
        <el-form class="login-form"
                 :rules="rules"
                 ref="loginForm"
                 :model="loginForm">
            <h3 class="title">后台管理系统</h3>

            <el-alert :title="loginForm.errorMsg" type="error" v-show="loginForm.errorVisible">
            </el-alert>

            <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="login">
                </el-input>
            </el-form-item>

            <el-form-item style="width:100%;">
                <el-button size="medium" type="primary" style="width:100%;" @click.native="login" >
                    <span>登 录</span>
                </el-button>
            </el-form-item>

        </el-form>
    </div>
</template>

<script>
import {login} from "@/api/system";
import {setToken} from "@/lib/tokenUtil";

export default {
    name: "Login",
    data() {
        return {
            loginForm: {
                username: "",
                password: "",
                errorMsg:"",
                errorVisible: false
            },
            rules:{
                username:[
                    {required:true,message:"账户名不能为空",trigger:'blur'}
                ],
                password:[
                    {required:true,message:"账户名不能为空",trigger:'blur'}
                ]
            }
        };
    },
    methods:{
        login(){
            this.$refs.loginForm.validate((valid) =>{
                if(valid){
                    this.loginForm.errorVisible=false; //重置登录错误信息不可见
                    this.loginForm.errorMsg=null; //清空登录错误信息
                    login(this.loginForm.username,this.loginForm.password)
                        .then(res =>{
                            setToken(res.data)
                            this.$router.push("/")
                        })
                        .catch(err =>{
                            this.loginForm.errorVisible=true;
                            this.loginForm.errorMsg=err.message;
                        })
                }
            })
        }
    }
}
</script>
<style rel="stylesheet/scss" lang="scss">
    .login {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        background-image: url("../assets/img/login-bg.jpg");
        background-size: cover;
    }
    .login-form {
        border-radius: 6px;
        background-color: rgba(255,255,255,0.7);
        width: 400px;
        padding: 25px 25px 5px 25px;

        .el-input {
            height: 38px;
            input {
                height: 38px;
            }
        }

    }
</style>